﻿using RecruitStudents.Client.BLL;
using RecruitStudents.Client.Examinee;
using RecruitStudents.Utility;
using RecruitStudents.Utility.Const;
using RecruitStudents.Utility.Helper;
using RecruitStudents.Utility.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RecruitStudents.Client.OnSiteSign
{
    public partial class OnSiteSign_OnSiteSignForm_List : BaseForm
    {
        #region 读卡器
        public int iRetUSB = 0;
        public int iRetCOM = 0;

        public StringBuilder name;      //姓名
        public String sex;              //性别
        public String people;           //民族，护照识别时此项为空
        public String birthday;         //出生日期
        public String address;          //地址，在识别护照时导出的是国籍简码
        public string number;           //地址，在识别护照时导出的是国籍简码
        public string signdate;         //签发日期，在识别护照时导出的是有效期至 
        public string validtermOfStart; //有效起始日期，在识别护照时为空
        public string validtermOfEnd;   //有效截止日期，在识别护照时为空

        //扫描结构：
        [StructLayout(LayoutKind.Sequential, Size = 16, CharSet = CharSet.Ansi)]
        public struct IDCARD_ALL
        {
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 30)]
            public char name;               //姓名
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 3)]
            public char sex;                //性别
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
            public char people;             //民族，护照识别时此项为空
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
            public char birthday;           //出生日期
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 70)]
            public char address;            //地址，在识别护照时导出的是国籍简码
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)]
            public char number;             //地址，在识别护照时导出的是国籍简码
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 30)]
            public char signdate;           //签发日期，在识别护照时导出的是有效期至 
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
            public char validtermOfStart;   //有效起始日期，在识别护照时为空
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
            public char validtermOfEnd;     //有效截止日期，在识别护照时为空
        }

        private void InitCardData()
        {
            try
            {
                int iPort;
                for (iPort = 1001; iPort <= 1016; iPort++)
                {
                    iRetUSB = CheckIDCard.CVR_InitComm(iPort);
                    if (iRetUSB == 1)
                        break;
                }

                for (iPort = 1; iPort <= 4; iPort++)
                {
                    iRetCOM = CheckIDCard.CVR_InitComm(iPort);
                    if (iRetCOM == 1)
                        break;
                }

                if ((iRetCOM == 1) || (iRetUSB == 1))
                {
                    this.groupSFZ.Text = "设置、扫描区（初始化成功）";
                }
                else
                {
                    this.groupSFZ.Text = "设置、扫描区（初始化失败）";
                }
            }
            catch
            {

            }
        }

        #endregion
        ServiceOnSiteSign service = new ServiceOnSiteSign();
        ServiceComm bllComm = new ServiceComm();
        ServiceBase serviceBase = new ServiceBase();
        public OnSiteSign_OnSiteSignForm_List()
        {
            InitializeComponent();
            gridControl1.AllowDrop = true; // 确保能够拖拽   
            gridView1.OptionsBehavior.Editable = false;
            this.Text = "签到控制中心 【" + "考点：" + SessionerHelper.ExamPlaceName + "             专业：" + SessionerHelper.SpecialityKinds + "             考试级别：" + SessionerHelper.ExamLevelName + "】";
            InitCardData();
            txtIdCard.KeyPress += txtIdCard_KeyPress;
            ClearTextBox();
            BoundGrid_QD();
            AddControl();
        }

        private void BoundGrid_QD()
        {
            using (DataTable dt = service.GetTB_Pad_SignedTable_New(SessionerHelper.ExaminationID, SessionerHelper.SystemYear))
            {
                gridControl1.DataSource = dt;
            }
        }

        private void ClearTextBox()
        {
            //txtIdCard.Text = "";
            lbGuid.Text =
            lbCXJG.Text =
            lbKSZG.Text =
            lbKSJB.Text =
            lbXM.Text =
            lbSFZH.Text =
            lbKSH.Text =
            lbZKZH.Text =
            lbSYD.Text =
            lbLXDH.Text =
            lbYYZB.Text =
            lbYYSJ.Text =
            lblPayFee.Text = "";
        }
        #region 身份证输入框回车事件
        private void txtIdCard_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                if (CheckIDCard.CheckTextEditIdCardNo(txtIdCard, e))
                {
                    QueryStudentInfo();
                }
            }
        }
        #endregion

        #region 身份证查询考生信息
        private void QueryStudentInfo()
        {
            ClearTextBox();
            string strIdentityCard = txtIdCard.Text;
            DataTable dt = service.CheckTB_Pad_Signed_New(SessionerHelper.SpecialityKindsNO, SessionerHelper.ExamLevel, SessionerHelper.ExamPlaceID, strIdentityCard, SessionerHelper.SystemYear);
            if (dt == null || dt.Rows.Count <= 0)
            {
                lbCXJG.Text = "没有查到该考生信息或未进行抽签。";
                DevHelper.ShowErrorMessageBox("没有查到该考生信息或未进行抽签!");
                txtIdCard.Focus();
                txtIdCard.SelectAll();
                return;
            }
            else if (dt.Rows.Count > 1)
            {
                lbCXJG.Text = "异常，多条该考生信息。";
                txtIdCard.Focus();
                txtIdCard.SelectAll();
                return;
            }
            else if (dt.Rows[0]["SignedTime"].ToSafeString() != "")
            {
                if (dt.Rows[0]["State"].ToString().Trim() == "1")
                {
                    DevHelper.ShowErrorMessageBox("该考生已经在排队序列中!");
                    lbCXJG.Text = "已经在排队序列中。";
                    lbKSZG.Text = "无效";
                    txtIdCard.Focus();
                    txtIdCard.SelectAll();
                    return;
                }
                else
                {
                    DevHelper.ShowErrorMessageBox("该考生已经完成考试!");
                    lbCXJG.Text = "已经完成考试。";
                    lbKSZG.Text = "无效";
                    txtIdCard.Focus();
                    txtIdCard.SelectAll();
                    return;
                }
            }
            string strSignedID = dt.Rows[0]["SignedID"].ToSafeString();
            string strExamPlaceNO = dt.Rows[0]["ExamPlaceNO"].ToString().Trim();
            string strExamGrade = dt.Rows[0]["ExamLevel"].ToString().Trim();
            string strIsPass = dt.Rows[0]["IsPass"].ToString().Trim();
            string strIsPayFee1 = dt.Rows[0]["IsFee_First"].ToString().Trim();
            string strIsPayFee2 = dt.Rows[0]["IsFee_Second"].ToString().Trim();
            string strIsPayFee3 = dt.Rows[0]["IsFee_Third"].ToString().Trim();
            string strIsPayFee4 = dt.Rows[0]["IsFee_Fourth"].ToString().Trim();
            string strIsPayFee5 = dt.Rows[0]["IsFee_Fifth"].ToString().Trim();
            string strIsPayFee6 = dt.Rows[0]["IsFee_Sixth"].ToString().Trim();
            lbGuid.Text = dt.Rows[0]["SignUpStudentsSpecialityID"].ToString().Trim();
            lbCXJG.Text = "查询成功。";
            lbKSZG.Text = dt.Rows[0]["IsActive"].ToString().Equals("1") ? "有效" : "无效";

            lbKSJB.Text = ConstExamLevel.GetExamLevel(SessionerHelper.ExamLevel.ToSafeInt());
            //using (DataTable dtExamLevel = bllComm.GetExamLevelTable())
            //{
            //    DataRow[] drs = dtExamLevel.Select("DicNO='" + SessionerHelper.ExamLevel + "'");
            //    if (drs.Length > 0)
            //    {
            //        lbKSJB.Text = drs[0]["DicName"].ToSafeString();
            //    }
            //}
            lbXM.Text = dt.Rows[0]["Name"].ToString().Trim();
            lbSFZH.Text = dt.Rows[0]["IdentityCard"].ToString().Trim();
            lbKSH.Text = dt.Rows[0]["NMT_SignUpID"].ToString().Trim();
            lbZKZH.Text = dt.Rows[0]["AllowExamID"].ToString().Trim();
            lbSYD.Text = dt.Rows[0]["ExamProvinceName"].ToSafeString();
            lbLXDH.Text = dt.Rows[0]["LinkMobile"].ToString().Trim();
            string strGroupNO = string.Empty;
            string strGroupTime = string.Empty;
            bool flag_Chk = false;
            if (SessionerHelper.ExamLevel == "1")
            {
                strGroupNO = "AppointmentGroup_First";
                strGroupTime = "AppointmentGroupTime_First";
                #region 初试
                if (strIsPayFee1 == "1")
                {
                    lbKSZG.Text = "有效";
                    lblPayFee.Text = "已缴费";
                    flag_Chk = true;
                }
                else
                {
                    lbCXJG.Text = "未缴费。";
                    lbKSZG.Text = "无效";
                    txtIdCard.Focus();
                    txtIdCard.SelectAll();
                    return;
                }
                #endregion
            }
            TB_Sys_ExamPlaceSpecialityKindsGroupMapping modelGroup = serviceBase.GetExamPlaceSpecialityKindsGroupMappingModel(string.Empty, dt.Rows[0][strGroupNO] != null ? dt.Rows[0][strGroupNO].ToString() : "");
            if (modelGroup != null)
            {
                lbYYZB.Text = modelGroup.GroupName;
            }
            lbYYSJ.Text = dt.Rows[0][strGroupTime] != null ? dt.Rows[0][strGroupTime].ToString() : "";
            if (flag_Chk)
            {
                service.UpdateExamSigned(strSignedID, SessionerHelper.SystemYear);
                BoundGrid_QD();
                ClearTextBox();
                //TB_Exam_Signed model = service.GetExamSignedByID(strSignedID, SessionerHelper.SystemYear);
                //if (model != null)
                //{
                //    model.Attach();
                //    //model.SignedTime = bllComm.GetSystemDateTime();
                //    service.SaveExamSigned(model);
                //    BoundGrid_QD();
                //    ClearTextBox();
                //}
            }
            txtIdCard.Text = "";
        }
        #endregion

        private void AddControl()
        {
            this.xtraScrollableControl1.Controls.Clear();
            using (DataTable dtExamRoom = bllComm.GetExamRoomTableByEntretenimientohID(SessionerHelper.ExaminationID))
            {
                if (dtExamRoom != null)
                {
                    ExamRoomUserControl examRoom = null;
                    for (int i = 0; i < dtExamRoom.Rows.Count; i++)
                    {
                        examRoom = new ExamRoomUserControl(dtExamRoom.Rows[i]["ExamRoomNO"].ToSafeString(),
                            dtExamRoom.Rows[i]["ExamRoomName"].ToSafeString(), service, bllComm);

                        examRoom.Text = dtExamRoom.Rows[i]["ExamRoomName"].ToSafeString();
                        examRoom.Location = CalculatePoint(i, 4, examRoom.Height, examRoom.Width);
                        examRoom.Distribution += btn_Distribution_Click;
                        examRoom.GridViewDoubleClick += ExamRoomUserControl_gridView2_DoubleClick;
                        examRoom.ExamRoom_DragEnter += ExamRoomUserControl_OnExamRoom_DragEnter;
                        examRoom.ExamRoom_DragDrop += ExamRoomUserControl_OnExamRoom_DragDrop;
                        examRoom.SiteSign_Refresh += ExamRoomUserControl_SiteSign_Refresh;
                        examRoom.DataGridBind();
                        this.xtraScrollableControl1.Controls.Add(examRoom);
                    }
                }
            }
        }
        private void ExamRoomUserControl_SiteSign_Refresh(object sender, EventArgs e)
        {
            this.BoundGrid_QD();
        }
        private void ExamRoomUserControl_gridView2_DoubleClick(object sender, EventArgs e)
        {
            this.BoundGrid_QD();
        }

        private void btn_Distribution_Click(object sender, EventArgs e)
        {
            BoundGrid_QD();
            if (gridView1.Rows != null)
            {
                var examRoom = sender as ExamRoomUserControl;
                examRoom.gridView = this.gridView1;
                examRoom.Distribute();
                examRoom.gridView = null;
                BoundGrid_QD();
            }
        }

        private void ExamRoomUserControl_OnExamRoom_DragEnter(object sender, DragEventArgs e)
        {
            ExamRoomUserControl exam = (ExamRoomUserControl)(((System.Windows.Forms.Control)(sender)).Parent).Parent;
            exam.SignedID = strSignedID;
        }

        private void ExamRoomUserControl_OnExamRoom_DragDrop(object sender, DragEventArgs e)
        {
            strSignedID = string.Empty;
            BoundGrid_QD();
        }

        private Point CalculatePoint(int sort, int columNum, int examRoomHeight, int examRoomWidth)
        {
            if (columNum == 0)
                columNum = 1;
            var m = sort % columNum;
            var b = sort / columNum;
            return new Point(m * (examRoomWidth + 2), b * (examRoomHeight + 2));
        }

        string strSignedID = string.Empty;
        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                strSignedID = "";
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = gridView1.CalcHitInfo(new Point(e.X, e.Y));
                if (info.InRow || info.InColumn)
                {
                    strSignedID = gridView1.Rows[info.RowHandle].DataRow["SignedID"].ToSafeString();
                    gridControl1.DoDragDrop(strSignedID, DragDropEffects.Move);
                }
            }
            else
            {
                strSignedID = "";
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = gridView1.CalcHitInfo(new Point(e.X, e.Y));
                if (info.InRow || info.InColumn)
                {
                    strSignedID = gridView1.Rows[info.RowHandle].DataRow["SignedID"].ToSafeString();
                    gridView1.ClearSelection();
                    gridView1.Rows[info.RowHandle].Selected = true;
                    cMStools.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }

        private void gridView1_MouseUp(object sender, MouseEventArgs e)
        {
            strSignedID = "";
        }

        private void gridControl1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void FresshAddData()
        {
            bool isFHTJ = false;
            Control.ControlCollection controlColl = this.xtraScrollableControl1.Controls;
            foreach (Control control in controlColl)
            {
                ExamRoomUserControl examRoom = (ExamRoomUserControl)control;
                examRoom.gridView = null;
                if (examRoom.IsAddDataDistri)//判断是否满足条件插入考场考生数据
                {
                    using (DataTable dt = service.GetTB_Pad_SignedTableTopOne_New(SessionerHelper.ExaminationID, SessionerHelper.SystemYear))
                    {
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            if (isFHTJ == false)
                            {
                                isFHTJ = true;
                            }
                            examRoom.Distribute(dt.Rows[0]);
                            //examRoom.DataGridBind();
                        }
                    }
                }
            }
            if (isFHTJ)
            {
                FresshAddData();
            }
        }



        private void btnFreshAll_Click(object sender, EventArgs e)
        {
            AutoDis();
        }


        private void AutoDis()
        {
            if (gridView1.Rows != null)
            {
                if (chkSX.Checked)
                {
                    FresshAddData();
                    BoundGrid_QD();
                    Control.ControlCollection controlColl = this.xtraScrollableControl1.Controls;
                    foreach (Control control in controlColl)
                    {
                        ExamRoomUserControl examRoom = (ExamRoomUserControl)control;
                        examRoom.DataGridBind();
                    }
                }
                else
                {
                    Control.ControlCollection controlColl = this.xtraScrollableControl1.Controls;
                    foreach (Control control in controlColl)
                    {
                        BoundGrid_QD();
                        ExamRoomUserControl examRoom = (ExamRoomUserControl)control;
                        examRoom.gridView = this.gridView1;
                        examRoom.Distribute();
                        examRoom.gridView = null;
                    }
                }
            }
            BoundGrid_QD();
        }


        private void cbAuto_CheckedChanged(object sender, EventArgs e)
        {
            bool isEnabled = false;
            if (cbAuto.Checked)
            {
                isEnabled = true;
                //cmbFreshTime.Enabled = false;
            }
            else
            {
                isEnabled = false;
                //cmbFreshTime.Enabled = true;
            }
            Control.ControlCollection controlColl = this.xtraScrollableControl1.Controls;
            foreach (Control control in controlColl)
            {
                ExamRoomUserControl examRoom = (ExamRoomUserControl)control;
                //examRoom.FreshTime = cmbFreshTime.Text;
                //examRoom.FreshTime 
                examRoom.SetBtnDistributeEnabled(!isEnabled);
                examRoom.SetTimerQueueEnabled(isEnabled);
            }
            if (cbAuto.Checked)
            {
                AutoDis();
            }
        }

        private void chkSFZ_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSFZ.Checked)
            {
                timer_ReadID.Enabled = true;
            }
            else
            {
                timer_ReadID.Enabled = false;
            }
        }

        private void OnSiteSign_OnSiteSignForm_List_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer_ReadID.Enabled = false;
            Control.ControlCollection controlColl = this.xtraScrollableControl1.Controls;
            foreach (Control control in controlColl)
            {
                ExamRoomUserControl examRoom = (ExamRoomUserControl)control;
                examRoom.SetTimerQueueEnabled(false);
            }
        }

        private void cbOrder_CheckedChanged(object sender, EventArgs e)
        {
            BoundGrid_QD();
        }

        private void csCancel_Click(object sender, EventArgs e)
        {
            string id = gridView1.GetFocusedRowCellValue("SignedID").ToString();
            service.DeleteExamSigned(id);
            BoundGrid_QD();
        }

        private void csView_Click(object sender, EventArgs e)
        {
            Examinee_ExameeDetailForm obj = new Examinee_ExameeDetailForm();
            obj.strNMT_SignUpID = gridView1.GetFocusedRowCellValue("NMT_SignUpID").ToString();
            obj.strType = "Look";
            obj.Run();
        }

        #region 身份证读卡器
        private void FillData()
        {
            try
            {
                int length = 30;
                //byte[] name = new byte[30];
                //CheckIDCard.GetPeopleName(ref name[0], ref length);
                byte[] number = new byte[30];
                length = 36;
                CheckIDCard.GetPeopleIDCode(ref number[0], ref length);
                //byte[] people = new byte[30];
                //length = 3;
                //CheckIDCard.GetPeopleNation(ref people[0], ref length);
                //byte[] validtermOfStart = new byte[30];
                //length = 16;
                //CheckIDCard.GetStartDate(ref validtermOfStart[0], ref length);
                //byte[] birthday = new byte[30];
                //length = 16;
                //CheckIDCard.GetPeopleBirthday(ref birthday[0], ref length);
                //byte[] address = new byte[30];
                //length = 70;
                //CheckIDCard.GetPeopleAddress(ref address[0], ref length);
                //byte[] validtermOfEnd = new byte[30];
                //length = 16;
                //CheckIDCard.GetEndDate(ref validtermOfEnd[0], ref length);
                //byte[] signdate = new byte[30];
                //length = 30;
                //CheckIDCard.GetDepartment(ref signdate[0], ref length);
                //byte[] sex = new byte[30];
                //length = 3;
                //CheckIDCard.GetPeopleSex(ref sex[0], ref length);
                txtIdCard.Text = System.Text.Encoding.GetEncoding("GB2312").GetString(number).Replace("\0", "");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        #endregion

        private void timer_ReadID_Tick(object sender, EventArgs e)
        {
            try
            {
                this.timer_ReadID.Enabled = false;
                //删除上次所拍的照片                
                if (System.IO.File.Exists(Application.StartupPath + "\\zp.bmp"))
                {
                    System.IO.File.Delete(Application.StartupPath + "\\zp.bmp");
                }
                if ((iRetCOM == 1) || (iRetUSB == 1))
                {
                    int authenticate = CheckIDCard.CVR_Authenticate();
                    if (authenticate == 1)
                    {
                        int readContent = CheckIDCard.CVR_Read_Content(4);
                        if (readContent == 1 || readContent == 2)
                        {
                            this.FillData();
                            this.QueryStudentInfo();
                            this.groupSFZ.Text = "设置、扫描区（读卡成功）";
                        }
                        else
                        {
                            this.groupSFZ.Text = "设置、扫描区（读卡操作失败）";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DevHelper.ShowErrorMessageBox(ex.ToString());
            }
            this.timer_ReadID.Enabled = true;
        }
        
    }
}
